# -*- coding: utf-8 -*-
'''
	openssl 相关
'''

import os,sys,subprocess,re,uuid,logging
from .. import config as C

#OPENSSL命令目录
if sys.platform == 'win32':
	CMD_OPENSSL = os.path.join(C.BASE_PATH, 'libs', 'openssl', 'openssl.exe')
	if not os.path.exists(CMD_OPENSSL):
		logging.error('not found %s !!!', CMD_OPENSSL)
else:
	CMD_OPENSSL = "openssl"

def AESEncrypto(key, iv, infile, outfile = None):
	'''
		AES加密
	'''
	if outfile == None:
		outfile = infile + "_en"
	subprocess.call([
		CMD_OPENSSL,
		'enc','-aes-128-cbc',
		'-in',infile,
		'-out',outfile,
		'-K',key,
		'-iv',iv
	])

def AESDecrypto(key, iv, infile, outfile = None):
	'''
	AES解密
	'''
	if outfile == None:
		outfile = infile + "_de"
	subprocess.call([
		CMD_OPENSSL,
		'enc','-aes-128-cbc','-d',
		'-in',infile,
		'-out',outfile,
		'-K',key,
		'-iv',iv
	])

def makeAESKey(passwd, salt = None):
	'''
	制作AES密钥
	'''
	if salt == None:
		salt = str(uuid.uuid4()).replace("-","").upper()[8:24]
	retdata = subprocess.check_output([CMD_OPENSSL,
		'enc','-aes-128-cbc',
		'-pass','pass:' + passwd,
		'-S',salt,'-P']).decode('gbk')
	key = None
	iv = None
	keymatch = re.compile(r'^\s*key\s*=\s*(.+)\s*$',re.M).search(retdata)
	if keymatch != None:
		key = keymatch.group(1)
	ivmatch = re.compile(r'^\s*iv\s*=\s*(.+)\s*$',re.M).search(retdata)
	if ivmatch != None:
		iv = ivmatch.group(1)
	return (key,iv)
	